package itbour.onetouchshow.base.mvp;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;

import com.lsjr.utils.NetUtils;
import com.utils.permission.Action;
import com.utils.permission.AndPermission;
import com.utils.permission.Permission;
import com.utils.permission.Setting;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.ParameterizedType;
import java.util.Calendar;
import java.util.List;

import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.BootPageActivity;
import itbour.onetouchshow.activity.BootPlayAeActivity;
import itbour.onetouchshow.activity.BootVideoPalyActivity;
import itbour.onetouchshow.activity.login.LoginActivity;
import itbour.onetouchshow.activity.login.SplashActivity;
import itbour.onetouchshow.activity.web.AdWebActivity;
import itbour.onetouchshow.base.ABaseActivity;
import itbour.onetouchshow.bean.AdDialogInfo;
import itbour.onetouchshow.bean.user.UserMakeTag;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.listener.PermissionListener;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.RuntimeRationale;
import itbour.onetouchshow.utils.StatusBarCompat;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.sharedpreference.PreferencesHelper;
import itbour.onetouchshow.widget.AdDialog;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public abstract class MVPBaseActivity<V extends BaseView, T extends BasePresenterImpl<V>> extends ABaseActivity implements BaseView {

    public T mPresenter;
    protected AdDialog adDialog;
    protected Handler mHandler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //System.gc();
        mHandler = new Handler();
    }

    @Override
    protected void initPresenter() {
        mPresenter = getInstance(this, 1);
        if (mPresenter != null) {
            mPresenter.attachView((V) this);
        }
    }

    @Override
    public void onBackPressed() {
        if (adDialog != null && adDialog.isShowing()) {
            adDialog.dismiss();
        } else {
            dismissProgressDialog();
            super.onBackPressed();
        }
    }


    public Context getViewContext() {
        return this;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        mPresenter = null;
    }

    public <T> T getInstance(Object o, int i) {
        try {
            return ((Class<T>) ((ParameterizedType) (o.getClass()
                    .getGenericSuperclass())).getActualTypeArguments()[i])
                    .newInstance();
        } catch (InstantiationException e) {
            //  e.printStackTrace();
        } catch (IllegalAccessException e) {
            //  e.printStackTrace();
        } catch (ClassCastException e) {
            // e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initTitle() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Settings.System.canWrite(this);
        }
        setTopLeftButton(R.mipmap.return_icon).
                setTitleTextColor(UIUtils.getColor(R.color.white)).
                setBackgroundColor(UIUtils.getColor(R.color.black));
        getToolBarView().getLeftimageView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        setImmersionBarBlack();
        getToolBarView().setBackgroundColor(getResources().getColor(R.color.app_status_bar_color));
    }

    protected void setImmersionBarBlack() {
        //import com.githang.statusbar.StatusBarCompat;
        StatusBarCompat.setStatusBarColor(this, UIUtils.getColor(R.color.app_status_bar_color));
        // SystemBarHelper.tintStatusBar(this, UIUtils.getColor(R.color.apptheme),0);
    }


    @Override
    protected void initView() {

    }

    @Override
    public int getFragmentContentId() {
        return 0;
    }

    protected void loginResultOpen(Class<?> pClass) {
//        LogingStatusListener.getInstance().checkLogin(new LogingStatusListener.LoginForCallBack() {
//            @Override
//            public void callBack() {
//                openActivity(pClass);
//            }
//        });
    }


    public boolean checkNetWork() {
        if (!NetUtils.isConnected(UIUtils.getContext())) {
            T_.showCustomToast("请检查网络");
            return false;
        }
        return true;
    }

    public void returnCheckNetWork() {
        if (!NetUtils.isConnected(UIUtils.getContext())) {
            T_.showCustomToast("请检查网络");
            return;
        }
    }


    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dataEvent(UserMakeTag userMakeTag) {

    }


    /**
     * 统一权限管理
     * Request permissions.
     */
    public void requestPermission(PermissionListener listener, String... permissions) {
        AndPermission.with(this)
                .runtime()
                .permission(permissions)
                .rationale(new RuntimeRationale())
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        /**
                         * 成功
                         */
                        listener.onGranted();
                        // toast(R.string.successfully);
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        //toast(R.string.failure);
                        L_.e("所拒绝的权限" + TextUtils.join("\n", data));
                        /**
                         * 拒绝
                         */
                        listener.onDenied(data);
                        //如果多次被用户拒绝就让用户进入设置页面
                        if (AndPermission.hasAlwaysDeniedPermission(MVPBaseActivity.this, data)) {
                            showSettingDialog(MVPBaseActivity.this, data);
                        }
                    }
                })
                .start();
    }


    /**
     * Display setting dialog.
     * <p>
     * 进入设置页面
     */
    public void showSettingDialog(Context context, final List<String> permissions) {
        List<String> permissionNames = Permission.transformText(context, permissions);
        String message = context.getString(R.string.message_permission_always_failed, TextUtils.join("\n", permissionNames));
        new AlertDialog.Builder(context)
                .setCancelable(false)
                .setTitle(R.string.title_dialog)
                .setMessage(message)
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        setPermission();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }


    /**
     * Set permissions.
     */
    private void setPermission() {
        AndPermission.with(this)
                .runtime()
                .setting()
                .onComeback(new Setting.Action() {
                    @Override
                    public void onAction() {
                        //Toast.makeText(MainActivity.this, R.string.message_setting_comeback, Toast.LENGTH_SHORT).show();
                    }
                })
                .start();
    }

    //2.3增加弹框
    @Override
    protected void onResume() {
        super.onResume();
        initAdDialog();
    }

    protected void initAdDialog() {
        //增加分享弹框
        final AdDialogInfo dialogInfo = PreferencesHelper.getData(AppConst.KEY_DIALOG_INFO, AdDialogInfo.class);
        if (dialogInfo != null) {
            //activity在前台显示
            if (isForeground(this)) {
                //欢迎页不需要弹框
                if (this instanceof AdWebActivity || this instanceof SplashActivity || this instanceof LoginActivity || this instanceof BootPageActivity
                        || this instanceof BootPlayAeActivity || this instanceof BootVideoPalyActivity) {
                    PreferencesHelper.saveData(AppConst.KEY_IS_GO_TO_BACKGROUND, false);
                    return;
                }
                Log.e("AdDialogInfo", this.getLocalClassName());

                // 1, 仅 APP 打开时判断显示, 2 仅 APP 从后台进入前台时判断显示, 3 标记 APP 打开, 后台进入前台均显示
                if (dialogInfo.getDisplayType() == 2 || dialogInfo.getDisplayType() == 3) {
                    //从后台进入的该页面
                    Boolean isFormBackground = PreferencesHelper.getData(AppConst.KEY_IS_GO_TO_BACKGROUND, Boolean.class);
                    if (isFormBackground != null && isFormBackground) {
                        showAdDialog(dialogInfo);
                    }

                }
            }
        }
    }

    public void showAdDialog(AdDialogInfo dialogInfo) {
        //先前已经弹框过则不再弹出
        if (adDialog != null && adDialog.isShowing()) return;
        Long timeLastShow = PreferencesHelper.getData(AppConst.KEY_DIALOG_SHOW_TIME, Long.class);
        long timeNow = Calendar.getInstance().getTimeInMillis();
        //时间未达到间隔时间 不弹
        if (timeLastShow == null) timeLastShow = 0l;
        if ((timeNow - timeLastShow) / 1000 < dialogInfo.getDisplayInterval()) return;
        //延时0.3秒 不使用延时从后台进入即显示弹框 如果ad页面同时存在 体验效果不佳
        //延时 使页面先进入ad页面 再后台弹框 弹框的过程用户不可见
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (adDialog == null) {
                    adDialog = new AdDialog(MVPBaseActivity.this);
                }
                adDialog.show();
                adDialog.setHeightAndWidth(dialogInfo.getWindowW(), dialogInfo.getWindowH(), dialogInfo.getContentUrl());
            }
        }, 300);
    }

    public boolean isForeground(Activity activity) {
        return isForeground(activity, activity.getClass().getName());
    }

    //Activity是否在前台显示
    public boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }


}
